package cn.zhiquxing.test;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class NoSafeDataBuffer<T> {
    
    public static final int max_amount = 10;
    private List<T> data = new LinkedList<>();
    
    private AtomicInteger amount = new AtomicInteger(0);
    
    public void addElement(T element) throws Exception {
        if (amount.get() > max_amount) {
            System.out.println("队列已满");
            return;
        }
        data.add(element);
        System.out.println(element.toString());
        amount.incrementAndGet();
        
        if (data.size() != amount.get()) {
            throw new Exception(amount + "!=" + data.size());
        }
    }
    
    public T fetchElement() throws Exception {
        if (amount.get() <= 0) {
            System.out.println("队列空了");
            return null;
        }
        T element = data.remove(0);
        System.out.println(element.toString());
        amount.decrementAndGet();
        if (data.size() != amount.get()) {
            throw new Exception(amount + "!=" + data.size());
        }
        return element;
    }
}
